package com.bst.bsj.jetty.server;

import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.util.thread.ExecutorThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;

import com.bst.bsj.spring.util.AppSettings;

public class JettyServer {

	private static Server server = null;

	private static final Logger logger = Logger.getLogger(JettyServer.class);

	public void run() throws Exception {
		if (server != null && server.isRunning()) {
			logger.warn("wine-metadata server has been start.");
			return;
		}

		server = new Server();
		server.setConnectors(getConnectors());
		server.setThreadPool(getThreadPool());
		server.setStopAtShutdown(true);
		server.setSendServerVersion(true);

		HandlerCollection handlers = new HandlerCollection();
		handlers.addHandler(getWebAppContext());
		handlers.addHandler(getRequestLogHandler());
		server.setHandler(handlers);

		server.start();
		logger.info("wine-metadata server launches, success.");
		server.join();
	}

	private Connector[] getConnectors() {
		return new Connector[] { new JettyConnector() };
	}

	private ThreadPool getThreadPool() {
		final int corePoolSize = AppSettings.getInstance().getInt("jetty.threadPool.corePoolSize", 50);
		final int maxPoolSize = AppSettings.getInstance().getInt("jetty.threadPool.maxPoolSize", 100);
		logger.info(String.format("Jetty Server thread pool:[corePoolSize=%d, maxPoolSize=%d]", corePoolSize,
				maxPoolSize));
		return new ExecutorThreadPool(corePoolSize, maxPoolSize, 60, TimeUnit.SECONDS);
	}

	private WebAppContext getWebAppContext() {

		String path = JettyServerLauncher.class.getResource("/").getFile().replaceAll("/target/(.*)", "")
				+ "/src/main/webapp";
		 WebAppContext webAppContext = new WebAppContext(path, "/");
		 //webAppContext.setInitParameter("dirAllowed", "false");
		 webAppContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
		 return webAppContext;
	}

	protected RequestLogHandler getRequestLogHandler() {
		RequestLogHandler logHandler = new RequestLogHandler();
		NCSARequestLog requestLog = new NCSARequestLog("jetty-yyyy_MM_dd.access.log");
		requestLog.setAppend(true);
		requestLog.setLogServer(true);
		requestLog.setExtended(false);
		requestLog.setLogTimeZone(TimeZone.getDefault().getID());
		requestLog.setLogLatency(true);
		requestLog.setLogDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
		logHandler.setRequestLog(requestLog);
		return logHandler;
	}

	public void stop() throws Exception {
		if (server != null) {
			server.stop();
			server = null;
		}
	}
}
